<template>
    <el-container class="container">
      <!-- 左侧树 -->
      <el-aside width="300px" class="aside">
        <div class="btn-group">
          <el-button type="primary" size="mini" plain @click="addBrotherNode">添加同级文件夹</el-button>
          <el-button type="primary" size="mini" plain @click="addChildNode">添加子文件夹</el-button>
        </div>
        <el-tree
          :data="treeData"
          node-key="id"
          :props="{ label: 'name' }"
          highlight-current
          default-expand-all
          :expand-on-click-node="false"
          :render-content="renderContent"
          @current-change="onTreeNodeChecked">
        </el-tree>
      </el-aside>
      <!-- 右侧顶部筛选 -->
      <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="作业" prop="descrip">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入作业"
              clearable
              size="small"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="triggerOpen"
            >添加作业</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleExport"
            >导出选中</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
            >删除选中</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              @click="handleExportAll"
            >导出全部</el-button>
          </el-col>
        </el-row>
        <!-- 右侧表格 -->
        <el-table v-loading="loading" :data="paperList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="作业" align="center" prop="name" />
          <el-table-column label="创建者" align="center" prop="createByName" />
          <el-table-column label="创建日期" align="center" prop="createTime" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          v-show="total>0"
          :total="total"
          :page.sync="pageData.pageNum"
          :limit.sync="pageData.pageSize"
          @pagination="getList"
        />
        <!-- 添加文件夹对话框 -->
        <el-dialog title="添加文件夹" @close="onDirClose" :visible.sync="addDirVisible">
          <el-input v-model="dirName" placeholder="请填写文件夹名称"></el-input>
          <span slot="footer" class="dialog-footer">
            <el-button @click="onDirClose">取 消</el-button>
            <el-button type="primary" @click="onDirConfirm">确 定</el-button>
          </span>
        </el-dialog>
        <!-- 添加或修改作业弹窗 -->
        <paper-edit-drawer
          :open.sync="open"
          :search="queryParams"
          :initData="record"
          paperType="Homework"
          :libId="curNode.id"
          @onOk="handleOk"
        />
        <!-- 作业详情弹窗 -->
        <!-- <paper-detail-drawer :open.sync="open" :libId="curNode.id" @onOk="handleOk" /> -->
      </div>
    </el-container>
  </template>
  
  <script>
  import {
    getDirTree,
    addDirTreeNode,
    delDirTreeNode,
    listPaper,
    getPaper,
    delPaper
  } from "@/api/publicManage/homework";
  import PaperEditDrawer from './components/paperEditDrawer/index.vue';
  import PaperDetailDrawer from './components/paperDetailDrawer/index.vue';
  
  export default {
    name: "Homework",
    components: { PaperEditDrawer, PaperDetailDrawer },
    data() {
      return {
        paperType: 'Homework',
        // 左侧树
        treeData: [],
        curNode: {},
        addDirVisible: false,
        dirName: '',
        // 弹窗显隐
        open: false,
        // 遮罩层
        loading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 作业表格数据
        paperList: [],
        // 查询参数
        queryParams: {
          isPublic: 1,
          courseId: -1,
          name: '',
        },
        // 分页参数
        pageData: {
          pageNum: 1,
          pageSize: 10,
        },
        record: {}
      };
    },
    created() {
      this.fetchTreeData();
      this.getList();
    },
    methods: {
      // 获取左侧菜单树
      fetchTreeData() {
        const { queryParams: { isPublic, courseId }, paperType } = this;
        getDirTree({ isPublic, courseId, paperType }).then(({ code, data }) => {
          if (code === 200) {
            this.treeData = data instanceof Array ? data : [data];
          }
        });
      },
      onTreeNodeChecked(node) {
        this.curNode = node;
        this.getList();
      },
      onDirClose() {
        this.addDirVisible = false;
        this.dirName = '';
      },
      onDirConfirm() {
        this.addDirVisible = false;
        const { paperType, curNode: { targetId }, queryParams: { isPublic, courseId } } = this;
        const reqBody = { name: this.dirName, parentId: targetId, isPublic, courseId, paperType };
        const loading = this.$loading({ lock: true });
        addDirTreeNode(reqBody).then(() => {
          loading.close();
          this.fetchTreeData();
        }).catch(() => {
          loading.close();
        });
      },
      addBrotherNode() {
        const { id, parentId } = this.curNode;
        if (!id) {
          this.$message({
            message: '请选择文件夹',
            type: 'warning'
          });
        } else {
          this.curNode = { ...this.curNode, targetId: parentId };
          this.addDirVisible = true;
        }
      },
      addChildNode() {
        const { id } = this.curNode;
        let targetId = -1;
        if (id) targetId = id;
        this.curNode = { ...this.curNode, targetId };
        this.addDirVisible = true;
      },
      triggerOpen() {
        if (!this.curNode.id) {
          this.$message({
            message: '请先选择文件夹',
            type: 'warning'
          });
        } else {
          this.record = {};
          this.open = true;
        }
      },
      async handleOk({ formData, submitFunc }) {
        const { isPublic, courseId } = this.queryParams;
        await submitFunc({ ...formData, isPublic, courseId });
        this.open = false;
        this.getList();
      },
      dirEdit(e, data) {
        e.stopImmediatePropagation();
        console.log(data);
      },
      dirDel(e, data) {
        e.stopImmediatePropagation();
        const ids = [data.id];
        this.$modal.confirm('是否确认删除该文件夹？').then(function() {
        return delDirTreeNode(ids);
      }).then(() => {
        this.fetchTreeData();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
      },
      // 自定义左侧树条目
      renderContent(_, { node, data }) {
        return (
          <span class="custom-tree-node">
            <div class="tree-node-label" title={node.label}>{node.label}</div>
            <div class="tree-node-right">
              <i class="el-icon-edit icon-show" on-click={(e) => this.dirEdit(e, data)}></i>
              <i class="el-icon-delete icon-show" on-click={(e) => this.dirDel(e, data)}></i>
            </div>
          </span>
        );
      },
      filterObjShallow(obj) {
        const result = {};
        Object.keys(obj).map(item => {
          if (!['', null, NaN].includes(obj[item]) && obj[item]?.length != 0) {
            result[item] = obj[item];
          }
        });
        return result;
      },
      /** 查询作业列表 */
      getList() {
        this.loading = true;
        const params = JSON.parse(JSON.stringify(this.queryParams));
        params.libPath = this.curNode.path || null;
        const diff = params.difficulty ? Number(params.difficulty) : null;
        listPaper(this.filterObjShallow({ ...params, difficulty: diff }), this.pageData).then(response => {
          this.paperList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        });
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.pageData.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        const id = row.id;
        getPaper(id).then(response => {
          this.record = response.data;
          this.open = true;
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm('是否确认删除作业编号为"' + ids + '"的数据项？').then(function() {
          return delPaper(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('question/question/export', {
          ...this.queryParams
        }, `question.xlsx`)
      },
      /** 导出所有按钮操作 */
      handleExportAll() {
        this.download('question/question/exportAll', {}, `question.xlsx`)
      }
    }
  };
  </script>
  
  <style lang="scss" scoped>
  @import './index.scss';
  </style>